package com.example.gouwu2;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

public class CartActivity extends AppCompatActivity {

    private ListView cartListView;
    private ImageButton btnFanhui;
    private ArrayList<CartManager.CartItem> cartItems = new ArrayList<>();
    private CartAdapter adapter;
    private Button btnJiesuan;

    private FrameLayout navHome, navCart, navMain;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);

        btnFanhui = findViewById(R.id.fanhui);
        cartListView = findViewById(R.id.cart_list);
        btnJiesuan = findViewById(R.id.cart_anniu); // 结算按钮

        navHome = findViewById(R.id.nav_home);
        navCart = findViewById(R.id.nav_cart);
        navMain = findViewById(R.id.nav_main);

        btnFanhui.setOnClickListener(v -> finish());

        btnJiesuan.setOnClickListener(v -> {
            if (cartItems.isEmpty()) {
                Toast.makeText(CartActivity.this, "购物车是空的，请先添加商品", Toast.LENGTH_SHORT).show();
            } else {
                CartManager.getInstance().clearCart();

                Toast.makeText(CartActivity.this, "已结算，感谢您的购买！", Toast.LENGTH_LONG).show();

                refreshCartData();
            }
        });

        refreshCartData();

        navCart.setSelected(true);

        navHome.setOnClickListener(v -> navigateTo(HomeActivity.class));
        navCart.setOnClickListener(v -> refreshCartData());
        navMain.setOnClickListener(v -> navigateTo(MainActivity.class));
    }

    private void navigateTo(Class<?> targetActivity) {
        // 避免重复打开当前页面
        if (this.getClass() == targetActivity) return;

        Intent intent = new Intent(CartActivity.this, targetActivity);
        startActivity(intent);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    private void refreshCartData() {

        cartItems.clear();
        cartItems.addAll(CartManager.getInstance().getCartItems());

        if (adapter == null) {
            adapter = new CartAdapter(this, cartItems);
            cartListView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }
}